using System;
using System.Web.UI;
using System.Collections.Generic;
using UserInterface.Misc;
using Domain.Entities;
using System.IO;

namespace UserInterface.UserControls
{
    public partial class Attachments : UserControl
    {
        private const string AttachmentFileUploadIDPrefix = "attachment_upload_";
        private const string UploadedAttachmentIDPrefix = "uploaded_attachment_";

        private const string SessionAttachmentsKeyPrefix = "attachments_";
        private const string SessionAttachmentCounterKeyPrefix = "attachment_counter_";

        private Dictionary<int, Attachment> attachments;
        private Counter attachmentCounter;

        public IList<Attachment> InitialAttachments
        {
            set
            {
                attachments.Clear();
                AttachmentsPlaceHolder.Controls.Clear();
                foreach (Attachment attachment in value)
                {
                    attachments[attachment.LocalId] = attachment;
                    AttachmentsPlaceHolder.Controls.Add(NewUploadedAttachment(attachment));
                    if (attachmentCounter.Current < attachment.LocalId)
                    {
                        attachmentCounter.Current = attachment.LocalId;
                    }
                }
            }
        }

        public IList<Attachment> AttachmentsWithFiles
        {
            get
            {
                List<Attachment> attachmentsWithFiles = new List<Attachment>();
                foreach (Attachment attachment in attachments.Values)
                {
                    if (attachment.HasFile)
                    {
                        attachmentsWithFiles.Add(attachment);
                    }
                }
                return attachmentsWithFiles;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            string uniqueKey = Request.Url.PathAndQuery;
            string attachmentsKey = SessionAttachmentsKeyPrefix + uniqueKey;
            string attachmentCounterKey = SessionAttachmentCounterKeyPrefix + uniqueKey;

            attachments = Session[attachmentsKey] as Dictionary<int, Attachment>;
            if (attachments == null)
            {
                attachments = new Dictionary<int, Attachment>();
                Session[attachmentsKey] = attachments;
            }
            else
            {
                foreach (Attachment attachment in attachments.Values)
                {
                    AddAttachment(attachment);
                }
            }

            attachmentCounter = Session[attachmentCounterKey] as Counter;
            if (attachmentCounter == null)
            {
                attachmentCounter = new Counter();
                Session[attachmentCounterKey] = attachmentCounter;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                HandleUploadedFiles();
            }
        }

        private void HandleUploadedFiles()
        {
            List<Control> controlsToAdd = new List<Control>();
            List<Control> controlsToRemove = new List<Control>();
            foreach (Control control in AttachmentsPlaceHolder.Controls)
            {
                AttachmentFileUpload upload = control as AttachmentFileUpload;
                if (upload != null && upload.HasFile)
                {
                    //TODO
                    //int localId = upload.Attachment.LocalId;
                    //Attachment attachment = attachments[localId];
                    //string tempPath = System.IO.Path.GetTempFileName();
                    //upload.SaveAs(tempPath);
                    //attachment.FilePath = tempPath;
                    //attachment.FileName = upload.FileName;
                    //attachment.FileLength = upload.ContentLength;
                    //attachment.FileType = upload.ContentType;
                    //controlsToAdd.Add(NewUploadedAttachment(attachment));
                    //controlsToRemove.Add(upload);
                }
            }
            foreach (Control control in controlsToAdd)
            {
                AttachmentsPlaceHolder.Controls.Add(control);
            }
            foreach (Control control in controlsToRemove)
            {
                AttachmentsPlaceHolder.Controls.Remove(control);
            }
        }

        protected void AddAttachmentButton_Click(object sender, EventArgs e)
        {
            //TODO
            //Attachment attachment = new Attachment();
            //int localId = attachmentCounter.Next();
            //attachment.LocalId = localId;
            //attachments[localId] = attachment;
            //AddAttachment(attachment);
        }

        protected void AddAttachment(Attachment attachment)
        {
            UserControl control = attachment.HasFile
                ? (UserControl)NewUploadedAttachment(attachment)
                : (UserControl)NewAttachmentFileUpload(attachment);
            AttachmentsPlaceHolder.Controls.Add(control);
        }

        private AttachmentFileUpload NewAttachmentFileUpload(Attachment attachment)
        {
            AttachmentFileUpload upload = (AttachmentFileUpload)LoadControl("~/UserControls/AttachmentFileUpload.ascx");
            upload.ID = AttachmentFileUploadIDPrefix + attachment.LocalId;
            upload.Attachment = attachment;
            upload.Remove += AttachmentFileUpload_Remove;
            return upload;
        }

        private UploadedAttachment NewUploadedAttachment(Attachment attachment)
        {
            UploadedAttachment uploaded = (UploadedAttachment)LoadControl("~/UserControls/UploadedAttachment.ascx");
            uploaded.ID = UploadedAttachmentIDPrefix + attachment.LocalId;
            uploaded.Attachment = attachment;
            uploaded.Remove += UploadedAttachment_Remove;
            return uploaded;
        }

        protected void AttachmentFileUpload_Remove(object sender, EventArgs e)
        {
            AttachmentFileUpload upload = (AttachmentFileUpload)sender;
            attachments.Remove(upload.Attachment.LocalId);
            AttachmentsPlaceHolder.Controls.Remove(upload);
        }

        protected void UploadedAttachment_Remove(object sender, EventArgs e)
        {
            UploadedAttachment uploaded = (UploadedAttachment)sender;
            File.Delete(uploaded.Attachment.FilePath);
            attachments.Remove(uploaded.Attachment.LocalId);
            AttachmentsPlaceHolder.Controls.Remove(uploaded);
        }
    }
}